package com.fs.web.yz.controller;

import com.fs.common.baseMapper.UserMapper;
import com.fs.common.pojo.Order;
import com.fs.common.pojo.User;
import com.fs.common.service.UserService;
import com.fs.common.yzMapper.OrderMapper;
import com.fs.common.yzMapper.ProductMapper;
import com.fs.web.base.enums.CodeEnum;
import com.fs.web.base.utils.ApplicationUtils;
import com.fs.web.base.utils.DateUtils;
import com.fs.web.base.vo.JsonResponse;
import com.fs.wechat.service.WechatPayService;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author DeveloperKK
 * @desc 扫码支付充值
 * @creationTime 2019-09-02 16:03
 * @projectName yuezi-menu
 * @packageName com.fs.web.yz.controller
 */
@Slf4j
@Controller
@RequestMapping("/console/recharge/rewrite")
public class RechargeController {

    @Autowired
    private WechatPayService wxPayService;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;


    @RequestMapping("/viewRecharge")
    public String viewRecharge(){
        return "/console/recharge";
    }


    @ResponseBody
    @RequestMapping("/recharge")
    public JsonResponse recharge(HttpServletRequest request,String orderId){
        try {
            if (StringUtils.isNotBlank(orderId)) {
                Order order = orderMapper.selectById(orderId);
                if (order != null) {
                    WxPayNativeOrderResult result = wxPayService.createOrder(order);
                    if (result == null || result.getCodeUrl() == null) {
                        order.setOrderStatus("CLOSED");
                        orderMapper.updateById(order);
                        throw new WxPayException("微信下单失败！");
                    }
                    return JsonResponse.success(result);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            if (e instanceof WxPayException) {
                return JsonResponse.error(e.getMessage());
            }
        }
        return JsonResponse.error(CodeEnum.EX999);
    }


    @ResponseBody
    @RequestMapping("/queryOrder")
    public JsonResponse queryOrder(HttpServletRequest request,String orderId){
        try {
            if (StringUtils.isNotBlank(orderId)) {
                Order order =  orderMapper.selectById(orderId);
                String orderStatus = order.getOrderStatus();
                if (order != null && order.getVersion() == 0) {
                    WxPayOrderQueryResult result = wxPayService.queryOrder(null, order.getOutTradeNo());
                    if (result == null || "FAIL".equalsIgnoreCase(result.getReturnCode())) {
                        throw  new WxPayException("查询订单失败！");
                    }
                    order.setOrderStatus(result.getTradeState());
                    if ("SUCCESS".equalsIgnoreCase(result.getTradeState())) {
                        order.setTransactionId(result.getTransactionId());
                        order.setTradeType(result.getTradeType());
                        order.setTotalFee(result.getTotalFee());
                        order.setResultCode(result.getResultCode());
                        order.setSettlementTotalFee(result.getSettlementTotalFee());
                        if (result.getTimeEnd()!= null) {
                            order.setTimeEnd(DateUtils.parseDate(result.getTimeEnd(),"yyyyMMddHHmmss"));
                        }
                        userService.rechargeCount(ApplicationUtils.getUser().getUser().getId(),order);
                        User user = userMapper.selectById(ApplicationUtils.getUser().getUser().getId());
                        ApplicationUtils.updateSessionUser(user);
                        log.info("订单号："+order.getOutTradeNo()+" 充值成功，" + "套餐名称：" + order.getOrderName() +
                                "金额："+ order.getTotalFee()+"，次数："+order.getCheckNumber()+
                                "支付订单号："+order.getTransactionId());
                    }
                    if (!orderStatus.equals(order.getOrderStatus())) {
                        if ("REVOKED".equals(order.getOrderStatus())
                            || "CLOSED".equals(order.getOrderStatus())
                            || "REVOKED".equals(order.getOrderStatus())
                            || "SUCCESS".equals(order.getOrderStatus())) {
                            order.setVersion(1);
                        }
                        orderMapper.updateById(order);
                    }
                    return JsonResponse.success(order);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            if (e instanceof WxPayException) {
                return JsonResponse.error(e.getMessage());
            }
        }
        return JsonResponse.error(CodeEnum.EX999);
    }

    /**
     * 对外暴露的支付结果通知接口
     * @param xmlData
     * @return
     */
    @ResponseBody
    @PostMapping("/notifyPayResult")
    @ApiOperation(value = "对外暴露的支付结果通知接口")
    public String notifyPayResult(@RequestBody String xmlData){
        try {
            WxPayOrderNotifyResult result = wxPayService.wxPayOrderNotifyResult(xmlData);
            if (result != null) {
                Order order = fromResult(result);
                if (StringUtils.isNotBlank(order.getId()) && order.getVersion() == 0) {
                    if ("SUCCESS".equals(order.getResultCode())) {
                        order.setOrderStatus("SUCCESS");
                        userService.rechargeCount(ApplicationUtils.getUser().getUser().getId(),order);
                    } else {
                        order.setOrderStatus("PAYERROR");
                    }
                    orderMapper.updateById(order);
                }
                return WxPayNotifyResponse.success("成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return WxPayNotifyResponse.fail("失败！");
    }

    private Order fromResult(WxPayOrderNotifyResult result){
        Order order = new Order();
        if (result != null) {
            String tradeNo = result.getOutTradeNo();
            order= orderMapper.findByOutTradeNo(tradeNo);
            if (order != null) {
                order.setTotalFee(result.getTotalFee());
                order.setResultCode(result.getResultCode());
                order.setSettlementTotalFee(result.getSettlementTotalFee());
                if (result.getTimeEnd()!= null) {
                    order.setTimeEnd(DateUtils.parseDate(result.getTimeEnd(),"yyyyMMddHHmmss"));
                }
                order.setTradeType(result.getTradeType());
                order.setTransactionId(result.getTransactionId());
                order.setVersion(1);
            }
        }
        return order;
    }



}
